package cn.csc.module.product.controller.app.spu;

import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.framework.common.pojo.PageResult;
import cn.csc.framework.security.core.annotations.PreAuthenticated;
import cn.csc.module.member.api.user.MemberUserApi;
import cn.csc.module.member.api.user.dto.MemberUserRespDTO;
import cn.csc.module.order.api.order.OrderApi;
import cn.csc.module.product.api.category.dto.CategoryRespDTO;
import cn.csc.module.product.controller.admin.seachcontext.vo.SpuSeachContextCreateReqVO;
import cn.csc.module.product.controller.admin.seachcontext.vo.SpuSeachContextRespVO;
import cn.csc.module.product.controller.admin.spu.vo.SpuDataRespV2VO;
import cn.csc.module.product.controller.admin.spu.vo.SpuPageReqV2VO;
import cn.csc.module.product.controller.admin.spu.vo.SpuRespV2VO;
import cn.csc.module.product.controller.app.spu.vo.*;
import cn.csc.module.product.convert.seachcontext.SpuSeachContextConvert;
import cn.csc.module.product.convert.spu.SpuConvert;
import cn.csc.module.product.dal.dataobject.spu.SpuDO;
import cn.csc.module.product.service.category.CategoryService;
import cn.csc.module.product.service.seachcontext.SpuSeachContextService;
import cn.csc.module.product.service.spu.SpuV2Service;
import cn.hutool.core.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import static cn.csc.framework.common.pojo.CommonResult.success;
import static cn.csc.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 商品信息，选品相关
 *
 * @author liuchuang
 * @version 1.0
 * @date 2024/10/17 16:48
 * @modify
 */
@Api(tags = "用户APP - 商品信息v2")
@RestController("appSpuV2Controller")
@RequestMapping("/product/spu/v2")
@Validated
@Slf4j
@Setter
public class AppSpuV2Controller {

    @Autowired
    private SpuV2Service spuV2Service;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SpuSeachContextService spuSeachContextService;
    @Resource
    private OrderApi orderApi;
    @Resource
    private MemberUserApi memberUserApi;


//    @PostMapping("/create")
//    @Operation(summary = "创建商品", description = "创建商品")
//    @PreAuthenticated
//    public CommonResult<BigInteger> appCreateSpu(@Validated @RequestBody AppSpuCreateReqVO reqVO) {
//        return success(spuService.appCreateSpuV2(reqVO));
//    }

    @GetMapping("/index")
    @ApiOperation("首页为你推荐商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", required = false, value = "分类ID", example = "1", dataTypeClass = BigInteger.class)
    })
    public CommonResult<PageResult<SpuRespV2VO>> getSpuPage(SpuPageReqV2VO pageVO) {
        pageVO.setVerifyStatus(10);
        if (pageVO.getCategoryId() != null) {
            List<CategoryRespDTO> list = categoryService.topItemList(pageVO.getCategoryId());
            List<BigInteger> ids = list.stream().map(CategoryRespDTO::getId).collect(Collectors.toList());
            if (ids != null && !ids.isEmpty())
                pageVO.setCategoryList(ids);
        }
        PageResult<SpuDO> pageResult = spuV2Service.getSpuPageSingle(pageVO);
        Long userId = getLoginUserId();
        Optional.ofNullable(pageResult.getList()).ifPresent(s -> {
            s.forEach(t -> {
                t.setSeq(Integer.parseInt(RandomUtil.randomNumbers(6)));
                if (userId != null) {
                    CommonResult<MemberUserRespDTO> result = memberUserApi.getUser(userId);
                    if (result.getCode() == 0) {
                        //用戶表type: 5和15都代表采购商
                        if (result.getData() != null && (result.getData().getType() == 5 || result.getData().getType() == 15)) {
                            t.setMarketPriceFee(t.getShopPriceFee());
                        } else {
                            t.setMarketPriceFee(t.getPriceFee());
                        }
                    }
                } else {
                    t.setMarketPriceFee(t.getPriceFee());
                }
            });
        });
        Optional.ofNullable(pageResult.getList()).ifPresent(s -> {
            List<SpuDO> list = s.stream().sorted(Comparator.comparing(j -> j.getSeq(), Comparator.reverseOrder())).collect(Collectors.toList());
            pageResult.setList(list);
        });
        return success(SpuConvert.INSTANCE.convertV2Page(pageResult));
    }


    @GetMapping("/highProudct")
    @ApiOperation("首页好货速递")
    public CommonResult<List<AppSpuHighRespVO>> highProudct(@RequestHeader(value = "tenant-id", required = false) Integer tenantId) {
        List<AppSpuHighRespVO> list = spuV2Service.getHighProudct();
        Long userId = getLoginUserId();
        Optional.ofNullable(list).ifPresent(s -> {
            s.forEach(t -> {
                if (userId != null) {
                    CommonResult<MemberUserRespDTO> result = memberUserApi.getUser(userId);
                    if (result.getCode() == 0) {
                        t.getProductData().forEach(x -> {
                            //用戶表type: 5和15都代表采购商
                            if (result.getData() != null && (result.getData().getType() == 5 || result.getData().getType() == 15)) {
                                x.setMarketPriceFee(x.getShopPriceFee());
                            } else {
                                x.setMarketPriceFee(x.getPriceFee());
                            }
                        });
                    } else {
                        t.getProductData().forEach(x -> {
                            x.setMarketPriceFee(x.getPriceFee());
                        });
                    }
                } else {
                    t.getProductData().forEach(x -> {
                        x.setMarketPriceFee(x.getPriceFee());
                    });
                }
            });
        });
        return success(list);
    }

    @GetMapping("/getById")
    @ApiOperation("商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true, value = "商品ID", example = "1", dataTypeClass = BigInteger.class)
    })
    public CommonResult<SpuDataRespV2VO> getById(@RequestParam BigInteger id) {
        SpuDataRespV2VO respVO = spuV2Service.getSpuAppDetail(id);
        spuV2Service.addFraction(respVO);
        if (getLoginUserId() != null) {
            CommonResult<MemberUserRespDTO> result = memberUserApi.getUser(getLoginUserId());
            if (result.getCode() == 0) {
                //用戶表type: 5和15都代表采购商
                if (result.getData() != null && (result.getData().getType() == 5 || result.getData().getType() == 15)) {
                    respVO.setMarketPriceFee(respVO.getShopPriceFee());
                    respVO.getSkuAttr().forEach(s -> {
                        s.setMarketPriceFee(s.getShopPriceFee());
                    });
                } else {
                    respVO.setMarketPriceFee(respVO.getPriceFee());
                    respVO.getSkuAttr().forEach(s -> {
                        s.setMarketPriceFee(s.getPriceFee());
                    });
                }
            } else {
                respVO.setMarketPriceFee(respVO.getPriceFee());
                respVO.getSkuAttr().forEach(s -> {
                    s.setMarketPriceFee(s.getPriceFee());
                });
            }
        } else {
            respVO.setMarketPriceFee(respVO.getPriceFee());
            respVO.getSkuAttr().forEach(s -> {
                s.setMarketPriceFee(s.getPriceFee());
            });
        }
        return success(respVO);
    }

    @PostMapping("/searchProduct")
    @ApiOperation("搜索商品")
    public CommonResult<PageResult<AppSpuRespVO>> searchProduct(@RequestBody AppSpuSearchPageReqVO reqVO) {
        PageResult<AppSpuRespVO> respVO = spuV2Service.searchAppProduct(reqVO);
        Long userId = getLoginUserId();
        Optional.ofNullable(respVO.getList()).ifPresent(s -> {
            s.forEach(t -> {
                if (userId != null) {
                    CommonResult<MemberUserRespDTO> result = memberUserApi.getUser(userId);
                    if (result.getCode() == 0) {
                        //用戶表type: 5和15都代表采购商
                        if (result.getData() != null && (result.getData().getType() == 5 || result.getData().getType() == 15)) {
                            t.setMarketPriceFee(t.getShopPriceFee());
                        } else {
                            t.setMarketPriceFee(t.getPriceFee());
                        }
                    } else {
                        t.setMarketPriceFee(t.getPriceFee());
                    }
                } else {
                    t.setMarketPriceFee(t.getPriceFee());
                }
            });
        });
        return success(respVO);
    }

    @GetMapping("/searchText")
    @ApiOperation("搜索新增商品文字记录")
    public CommonResult<PageResult<AppSpuRespVO>> searchText(SpuSeachContextCreateReqVO reqVO) {
        spuSeachContextService.searchContext(reqVO);
        return success();
    }

    @PostMapping("/delSearch")
    @ApiOperation("搜索新增商品文字记录")
    @PreAuthenticated
    public CommonResult<Integer> delSearch() {
        return success(spuSeachContextService.deleteSpuSeachByUserId(BigInteger.valueOf(getLoginUserId())));
    }

    @GetMapping("/getContextList")
    @ApiOperation("获取用户搜索文字记录")
    public CommonResult<List<SpuSeachContextRespVO>> getContextList() {
        if (getLoginUserId() != null) {
            SpuSeachContextCreateReqVO reqVO = new SpuSeachContextCreateReqVO();
            reqVO.setUserId(BigInteger.valueOf(getLoginUserId()));
            return success(SpuSeachContextConvert.INSTANCE.convertList(spuSeachContextService.selectContextList(reqVO)));
        } else {
            return success();
        }
    }

    /**
     * 查询购物车商品数量
     *
     * @return
     */
    @GetMapping("/searchCartNum")
    @ApiOperation(value = "查询购物车商品数量")
    public CommonResult<Long> searchCartNum() {
        Long userId = getLoginUserId();
        if (userId == null) {
            return success();
        } else {
            return orderApi.searchCartNum(BigInteger.valueOf(userId));
        }
    }

    /**
     * 查询上新商品
     *
     * @return
     */
    @GetMapping("/selectIndexNew")
    @ApiOperation(value = "查询首页上新商品")
    public CommonResult<List<AppSpuRespVO>> selectIndexNew(AppSpuCreateReqVO reqVO) {
        reqVO.setLimitNum("limit 4");
        reqVO.setVerifyStatus(10);

        List<AppSpuRespVO> respVO = spuV2Service.selectIndexNew(reqVO);
        Long userId = getLoginUserId();
        Optional.ofNullable(respVO).ifPresent(s -> {
            s.forEach(t -> {
                if (userId != null) {
                    CommonResult<MemberUserRespDTO> result = memberUserApi.getUser(userId);
                    if (result.getCode() == 0) {
                        //用戶表type: 5和15都代表采购商
                        if (result.getData() != null && (result.getData().getType() == 5 || result.getData().getType() == 15)) {
                            t.setMarketPriceFee(t.getShopPriceFee());
                        } else {
                            t.setMarketPriceFee(t.getPriceFee());
                        }
                    }else{
                        t.setMarketPriceFee(t.getPriceFee());
                    }
                } else {
                    t.setMarketPriceFee(t.getPriceFee());
                }
            });
        });
        return success(respVO);
    }

    /**
     * 上新列表商品
     *
     * @return
     */
    @GetMapping("/selectLastNew")
    @ApiOperation(value = "上新列表商品")
    public CommonResult<List<AppCategoryRespVO>> selectLastNew(AppSpuCreateReqVO reqVO) {
        reqVO.setLimitNum("limit 30");
        reqVO.setVerifyStatus(10);
        return success(spuV2Service.selectLastNew(reqVO));
    }


    /**
     * 首页优惠商品
     *
     * @return
     */
    @GetMapping("/selectIndexDiscounted")
    @ApiOperation(value = "首页优惠商品")
    public CommonResult<List<AppSpuRespVO>> selectIndexDiscounted() {
        List<SpuDO> list = spuV2Service.selectdiscountedProduct();
        List<SpuDO> resultList = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            list.forEach(s -> {
                s.setSeq(Integer.parseInt(RandomUtil.randomNumbers(6)));
            });

            List<SpuDO> sortList = list.stream().sorted(Comparator.comparing(j -> j.getSeq(), Comparator.reverseOrder())).collect(Collectors.toList());
            //取出价格小于100元
            List<SpuDO> priceMInList = sortList.stream().filter(s -> s.getPriceFee().compareTo(new BigDecimal(100)) < 0).collect(Collectors.toList());

            if (priceMInList != null && !priceMInList.isEmpty() && priceMInList.size() > 4) {
                List<SpuDO> resList = priceMInList.stream().limit(4).collect(Collectors.toList());
                resultList.addAll(resList);
            } else
                resultList.addAll(priceMInList);
        }

        List<AppSpuRespVO> results = SpuConvert.INSTANCE.convertList3(resultList);
        getResultProduct(results);

        return success(results);
    }


    /**
     * 限时优惠列表商品
     *
     * @return
     */
    @GetMapping("/selectDiscounted")
    @ApiOperation(value = "限时优惠列表商品")
    public CommonResult<List<AppSpuRespVO>> selectDiscounted() {
        List<SpuDO> list = spuV2Service.selectdiscountedProduct();
        List<AppSpuRespVO> results = SpuConvert.INSTANCE.convertList3(list);
        getResultProduct(results);
        return success(results);
    }

    private void getResultProduct(List<AppSpuRespVO> results) {
        if (results != null && !results.isEmpty()) {
            Long userId = getLoginUserId();
            Random random = new Random();
            Optional.ofNullable(results).ifPresent(s -> {
                BigDecimal divi = new BigDecimal(100);
                s.forEach(t -> {
                    int i = random.nextInt(50) + 110;
                    if (userId != null) {
                        CommonResult<MemberUserRespDTO> result = memberUserApi.getUser(userId);
                        if (result.getCode() == 0) {
                            //用戶表type: 5和15都代表采购商
                            if (result.getData() != null && (result.getData().getType() == 5 || result.getData().getType() == 15)) {
                                t.setMarketPriceFee(t.getShopPriceFee());
                                t.setDiscountedPriceFee(t.getShopPriceFee().multiply(new BigDecimal(i).divide(divi)));
                            } else {
                                t.setMarketPriceFee(t.getPriceFee());
                                t.setDiscountedPriceFee(t.getPriceFee().multiply(new BigDecimal(i).divide(divi)));
                            }
                        } else {
                            t.setMarketPriceFee(t.getPriceFee());
                            t.setDiscountedPriceFee(t.getPriceFee().multiply(new BigDecimal(i).divide(divi)));
                        }
                    } else {
                        t.setMarketPriceFee(t.getPriceFee());
                        t.setDiscountedPriceFee(t.getPriceFee().multiply(new BigDecimal(i).divide(divi)));
                    }
                });
            });
        }
    }
}
